package com.palm.vue.integration;

import com.palm.vue.VueResourceLoader;
import org.noear.solon.Solon;
import org.noear.solon.SolonApp;
import org.noear.solon.core.AopContext;
import org.noear.solon.core.Plugin;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.web.staticfiles.StaticMappings;
import org.noear.solon.web.staticfiles.StaticMimes;

import java.net.URL;
import java.util.Date;

public class XPluginImp implements Plugin {
    protected static final Date modified_time = new Date();
    static int maxAge = -1;
    public static String vueVersion="2";
    public static int maxAge() {
        if (maxAge < 0) {
            if (Solon.cfg().isDebugMode()) {
                maxAge = 0;
            } else {
                maxAge = Solon.cfg().getInt("solon.staticfiles.maxAge", 600);
            }
        }
        return maxAge;
    }
    @Override
    public void start(AopContext context) {
        SolonApp app=Solon.global();
       //String mode= app.cfg().get("vue.mode","compile");
        vueVersion=app.cfg().get("vue.version","3");
        //debug模式直接响应内容
        boolean isDebug=false;
        VueHandler vueHandler= new VueHandler();
        JsTransformHandler jsTransformHandler= new JsTransformHandler();
        LessHandler lessHandler=new LessHandler();
        if (app.cfg().isDebugMode()) {
           // StaticMimes.instance().putIfAbsent(".vue", "text/html");
            StaticMimes.add(".vue","text/html");
            app.filter((ctx, chain) -> {
                if("GET".equals(ctx.method())){
                    String path=ctx.path();
                    if(path.endsWith(".js")){
                        jsTransformHandler.handle(ctx);
                        if(ctx.getHandled()){
                           return;
                        }
                    }else if(path.endsWith(".css")){
                        lessHandler.handle(ctx);
                    }
                    if(ctx.getHandled()){
                        return;
                    }
                }
                chain.doFilter(ctx);
            });
            /** 调试模式优先使用转换文件**/
//            app.before("**.js",MethodType.GET,jsTransformHandler);
//            app.before("**.css",MethodType.GET,lessHandler);
            isDebug=true;
        }

        VueResourceLoader.setVueVersion(vueVersion,!isDebug);
        VueResourceLoader.resourceLoader=path->{
            try {
                URL url= StaticMappings.find(path);
                if(url!=null){
                    return url.openStream();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        };
//        app.add("/js/vue.min.js",MethodType.GET,ctx -> {
//            ctx.setHandled(true);
//            String modified_since = ctx.header("If-Modified-Since");
//            String modified_now = modified_time.toString();
//            if (modified_since != null && maxAge() > 0 && modified_since.equals(modified_now)) {
//                ctx.headerSet("Cache-Control", "max-age=" + maxAge());
//                ctx.headerSet("Last-Modified", modified_now);
//                ctx.status(304);
//            } else {
//                if (maxAge() > 0) {
//                    ctx.headerSet("Cache-Control", "max-age=" + maxAge());
//                    ctx.headerSet("Last-Modified", modified_time.toString());
//                }
//                ctx.contentType("application/javascript");
//                ctx.headerSet("Content-Encoding","gzip");
//                ctx.status(200);
//                ctx.output(VueResourceLoader.getVue());
//            }
//        });
        //vue
        app.add("/js/vue.js",MethodType.GET,new CachedScriptHandler("/script/vue"+vueVersion+(!isDebug?".min":"")+".js",maxAge()));
        //loader
        if("2".equals(vueVersion)){
            app.add("/js/loader.min.js",MethodType.GET,new CachedScriptHandler("/script/loader"+vueVersion+".min.js",maxAge()));
            app.add("/less.js",MethodType.GET,new CachedScriptHandler("/script/less.min.js",maxAge()));
        }else{
            app.add("/js/loader.js",MethodType.GET,new CachedScriptHandler("/script/loader"+vueVersion+".min.js",maxAge()));
            app.add("/compiler.js",MethodType.GET,new CachedScriptHandler("/script/compiler.min.js",maxAge()));
        }
        //添加转换拦截，一般在调试模式下用（打包模式下，对应文件已经被编译成为了css和js文件）
        app.add("**.css",MethodType.GET,lessHandler);
        if(!isDebug){
            app.add("**.js",MethodType.GET,jsTransformHandler);
        }
        app.add("**.vue",MethodType.GET,vueHandler);
    }
}
